from time import time
import hashlib
import os

from flask import request, current_app
from flask_restful import Resource, reqparse
from flask_shop import models, db
from flask_shop.product import product_api, product_bp


class Products(Resource):

    def post(self):
        """
        增加商品
        :return:
        """
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('name', type=str, required=True, help='商品不能为空')
            parser.add_argument('price', type=float)
            parser.add_argument('number', type=int)
            parser.add_argument('introduce', type=str)
            parser.add_argument('weight', type=int)

            parser.add_argument('pics', type=list, location='json')
            parser.add_argument('attr_static', type=list, location='json')
            parser.add_argument('attr_dynamic', type=list, location='json')

            args = parser.parse_args()

            product = models.Product(
                name=args.get('name'),
                price=args.get('price'),
                number=args.get('number'),
                introduce=args.get('introduce'),
                weight=args.get('weight'),
                cid_one=args.get('cid_one'),
                cid_two=args.get('cid_two'),
                cid_three=args.get('cid_three')
            )
            db.session.add(product)
            db.session.commit()

            # 增加商品的图片
            for p in args.get('pcis'):
                pic = models.Picture(path=p, pid=product.id)
                db.session.add(pic)

            for a in args.get('attr_static'):
                attr = models.ProductAttr(pid=product.id, aid=a.get('id'), val=a.get('val'), _type='static')
                db.session.add(attr)

            for a in args.get('attr_dynamic'):
                attr = models.ProductAttr(pid=product.id, aid=a.get('id'), val=','.join(a.get('val')), _type='dynamic')
                db.session.add(attr)
            db.session.commit()
            return {'status': 200, 'msg': '增加商品成功'}
        except Exception as e:
            return {'status': 500, 'msg': '增加商品失败'}
        pass

    def get(self):
        """
        获取商品列表
        :return: dict
        """
        parser = reqparse.RequestParser()
        # 添加参数
        parser.add_argument('name', type=str, location='args')
        # 解析参数
        args = parser.parse_args()
        # 获取参数
        name = args.get('name')
        if name:
            product_list = models.Product.query.filter(models.Product.name.like(f'%{name}%')).all()
        else:
            product_list = models.Product.query.all()
        return {
            'status': 200,
            'msg': '获取商品列表成功',
            'data': [product.to_dict() for product in product_list]
        }


product_api.add_resource(Products, '/products')


class Product(Resource):

    def delete(self, id):
        """
        删除商品
        :return: dict
        """
        try:
            product = models.Product.query.get(id)
            db.session.delete(product)
            db.session.commit()
            return {'status': 200, 'msg': '删除商品成功'}
        except Exception as e:
            print(e)
            return {'status': 500, 'msg': '删除商品失败'}


product_api.add_resource(Product, '/product/<int:id>')


@product_bp.route('/upload_img/', methods=['POST'])
def upload_img():
    try:
        img_file = request.files.get('file')
        # 判断文件是否存在
        if not img_file:
            pass
        # 判断图片类型是否允许
        if allowed_img(img_file.filename):
            folder = current_app.config.get('UPLOAD_FOLDER')
            if not os.path.exists(folder):
                os.makedirs(folder)
            # 保存图片
            filename = md5_file() + '.' + img_file.filename.rsplit('.', 1)[1]
            img_file.save(f'{folder}/{filename}')
            data = {
                'path': f'/static/upload/{filename}',
                'url': f"http://127.0.0.1:5000/static/upload/{filename}"
            }
            return {'status': 200, 'msg': '上传图片成功', 'data': data}
        else:
            return {'status': 500, 'msg': '图片格式出错'}
    except Exception as e:
        return {'status': 500, 'msg': '图片上传失败'}


def allowed_img(filename):
    """ 判断文件名是否为允许的名字 """
    # 获取文件的后缀
    if '.' in filename:
        file = filename.rsplit('.', 1)[1]
        if file in current_app.config.get('ALLOWED_EXTENSIONS'):
            return True
    return False


def md5_file():
    """
    加密时间戳保存文件
    :return:
    """
    # 创建hashlib对象
    md5 = hashlib.md5()
    timestamp = str(time())
    md5.update(timestamp.encode())
    filename = md5.hexdigest()
    return filename
